package infostroy.bookagolf.components.dialogs;

import com.academysmart.bookagolf.config.ApplicationConfigValues;
import com.academysmart.bookagolf.i18n.Messages;
import com.academysmart.bookagolf.model.Equipment;
import com.academysmart.bookagolf.model.EquipmentSetItem;
import com.academysmart.bookagolf.model.Game;
import com.academysmart.bookagolf.model.Order;
import com.academysmart.bookagolf.model.OrderFilter;
import com.academysmart.bookagolf.model.OrderedGame;
import com.academysmart.bookagolf.provider.ClubProvider;
import com.academysmart.bookagolf.provider.EquipmentProvider;
import com.academysmart.bookagolf.provider.FieldProvider;
import com.academysmart.bookagolf.provider.GameProvider;
import com.academysmart.bookagolf.provider.OrderProvider;
import infostroy.bookagolf.common.Constants.Colors;
import infostroy.bookagolf.common.Constants.Dimensions;
import infostroy.bookagolf.common.Constants.Icons;
import infostroy.bookagolf.common.helpers.ComponentsHelper;
import infostroy.bookagolf.common.helpers.DateTimeHelper;
import infostroy.bookagolf.common.helpers.ImageHelper;
import infostroy.bookagolf.common.helpers.StringHelper;
import infostroy.bookagolf.components.controls.GolfRoundButton;
import infostroy.bookagolf.components.inputs.GolfCheckBox;
import infostroy.bookagolf.components.inputs.GolfComboBox;
import infostroy.bookagolf.components.inputs.GolfDecimalTextField;
import infostroy.bookagolf.components.inputs.GolfTextField;
import infostroy.bookagolf.components.panels.GolfRoundPanel;
import infostroy.bookagolf.components.panels.ScrollPanel;
import infostroy.bookagolf.components.table.GolfTable;
import infostroy.bookagolf.components.widgets.GolfCalendar;
import infostroy.bookagolf.model.GolfTableModel;
import infostroy.bookagolf.views.BookingPanel;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * Created by Andrew on 26.02.14.
 */
public class GolfAddBookingDialog extends GolfBaseDialog {

    public static final String TIME = Messages.PricesViewListGame_Time;
    public static final String BY = Messages.Common_By;
    public static final String FIELD = Messages.PricesViewListGame_Field;
    public static final String PLAYERS = Messages.PricesViewListGame_Players;
    public static final String PRICE = Messages.Order_price;
    public static final String TOTAL = Messages.OrderViewList_Total;
    public static final String EQUIPMENT = Messages.PricesViewListHire_Equipment;
    public static final String AMOUNT = Messages.Order_amount;
    public static final String PLAYER_NAME = Messages.OrderViewList_Name;

    private JPanel holderPanel;
    private JPanel labelComboBoxPanel;
    private JPanel gamesTablePanel;
    private JPanel equipmentTablePanel;
    private JPanel lastPanel;

    private JPanel datePanel;
    private JPanel holesPanel;
    private JPanel fieldPanel;

    private JPanel paidMoneyPanel;
    private JPanel buttonPanel;

    private JLabel dateLbl;
    private JLabel chosenDateLbl;
    private GolfCalendar calendarWidget;
    private JPanel calendarPanel;

    private JLabel timeLbl;
    private JComboBox gameStartJCB;
    private JLabel timeToLbl;
    private JComboBox gameEndToJCB;

    private JLabel holesLbl;
    private JComboBox holesJCB;

    private JLabel fieldLbl;
    private JComboBox fieldJCB;

    private GolfTable gamesTable;
    private GolfTableModel gamesTM;
    private JScrollPane gamesJSP;
    private GolfTable equipmentsTable;
    private GolfTableModel equipmentsTM;
    private JScrollPane equipmentsJSP;
    private List<Object[][]> gamesData;
    private String[] gamesColumnNames;
    private List<Object[][]> equipmentsData;
    private String[] equipmentsColumnNames;

    private JLabel paidMoneyLbl;
    private JTextField paidMoneyJTF;

    private JButton addBookingButton;

    private Long fieldId;
    private Date orderingDate;
    private int gameStart = 0;
    private int gameEnd = 0;
    List<OrderedGame> orderedGames;
    List<EquipmentSetItem> orderedEquipment;
    private Double gamesPrice;
    private Double equipmentPrice;
    private Double orderPrice;
    
    private BookingPanel orderTablePanel;
    private JLabel playerNameLbl;
    private JTextField playerNameJtf;
    private JLabel filtersLabel;

    public GolfAddBookingDialog(String title, Color background, Dimension dimension, Color titleColor, BookingPanel panel) {
        super(title, background, dimension, titleColor);

        this.orderTablePanel = panel;

        initPanels();

        initDatePanelContents();
        initTimePanelContents();
        initHolesPanelComponents();
        initFieldPanelComponents();

        initGamesTablePanelComponents();
        initEquipmentTablePanelComponents();
        initPaidMoneyPanelComponents();
        initButtonPanelComponents();

        addDatePanelContents();
        addTimePanelComponents();
        addHolesPanelComponents();
        addFieldPanelComponents();
        addLabelComboBoxPanelComponents();

        addGamesTablePanelComponents();
        addEquipmentTablePanelComponents();
        addPaidMoneyPanelComponents();
        addButtonPanelComponents();
        addLastPanelComponents();
        addContentPanelComponents();
    }

    @Override
    protected void initContent() {

    }

    private void initPanels() {
        holderPanel = new JPanel();
        holderPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        holderPanel.setLayout(new BoxLayout(holderPanel, BoxLayout.PAGE_AXIS));
        labelComboBoxPanel = new JPanel();
        labelComboBoxPanel.setPreferredSize(new Dimension(500,290));
//        labelComboBoxPanel.setLayout(new GridLayout(5,1,5,0));
        labelComboBoxPanel.setLayout(new GridLayout(6,1));

        gamesTablePanel = new JPanel();
        gamesTablePanel.setLayout(new BoxLayout(gamesTablePanel, BoxLayout.X_AXIS));
        equipmentTablePanel = new JPanel();
        equipmentTablePanel.setLayout(new BoxLayout(equipmentTablePanel, BoxLayout.X_AXIS));

        lastPanel = new JPanel();
        lastPanel.setLayout(new BoxLayout(lastPanel, BoxLayout.X_AXIS));

        datePanel = new JPanel();
        datePanel.setLayout(new BoxLayout(datePanel, BoxLayout.X_AXIS));

        holesPanel = new JPanel();
        holesPanel.setLayout(new BoxLayout(holesPanel, BoxLayout.X_AXIS));

        fieldPanel = new JPanel();
        fieldPanel.setLayout(new GridLayout(1, 2));

        paidMoneyPanel = new JPanel();
        paidMoneyPanel.setLayout(new BoxLayout(paidMoneyPanel, BoxLayout.X_AXIS));

        buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));

    }

    private void initDatePanelContents() {
        dateLbl = new JLabel(Messages.AddOrderView_Date);
        calendarPanel = new GolfRoundPanel();
        calendarPanel.setLayout(new BoxLayout(calendarPanel, BoxLayout.LINE_AXIS));
        calendarPanel.setPreferredSize(Dimensions.CALENDAR_ADD_BOOKING_DIALOG_DIM);
        chosenDateLbl = new JLabel();
        calendarPanel.add(chosenDateLbl);
        calendarPanel.add(Box.createHorizontalGlue());

        JButton calendarButton = ComponentsHelper.createButtonWithImg(ImageHelper
                .getInstance().loadImage(Icons.CALENDAR_ICON));
        calendarWidget = new GolfCalendar(calendarButton, new DateChangeListener());
        calendarButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                calendarWidget.show();
            }
        });
        calendarPanel.add(calendarButton);
    }

    private void initTimePanelContents() {
        timeLbl = new JLabel();
        timeLbl.setText(TIME);
        gameStartJCB = new GolfComboBox(getHours());
        gameStartJCB.setSelectedIndex(-1);
        gameStartJCB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                gameStart = Integer.parseInt((String) gameStartJCB.getSelectedItem());
                gamesTM.refreshModel(loadGamesData(fieldId, orderingDate, gameStart, gameEnd));
            }
        });

        timeToLbl = new JLabel();
        timeToLbl.setText(BY);
        gameEndToJCB = new GolfComboBox(getHours());
        gameEndToJCB.setSelectedIndex(-1);
        gameEndToJCB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                gameEnd = Integer.parseInt((String) gameEndToJCB.getSelectedItem());
                gamesTM.refreshModel(loadGamesData(fieldId, orderingDate, gameStart, gameEnd));
            }
        });
    }

    private void addDatePanelContents() {
        datePanel.add(Box.createRigidArea(new Dimension(10, 5)));
        datePanel.add(dateLbl);
        datePanel.add(Box.createRigidArea(new Dimension(25, 5)));
        datePanel.add(calendarPanel);
        datePanel.add(Box.createRigidArea(new Dimension(10, 5)));
        datePanel.add(timeLbl);
        datePanel.add(Box.createRigidArea(new Dimension(15, 5)));
        datePanel.add(gameStartJCB);
        datePanel.add(Box.createRigidArea(new Dimension(15, 5)));
        datePanel.add(timeToLbl);
        datePanel.add(Box.createRigidArea(new Dimension(15, 5)));
        datePanel.add(gameEndToJCB);
        datePanel.add(Box.createRigidArea(new Dimension(10, 5)));
    }


    private void addTimePanelComponents() {
    }

    private void initHolesPanelComponents() {
        holesLbl = new JLabel();
        holesLbl.setText(Messages.AddOrderView_Holes);
        holesJCB = new GolfComboBox();
        holesJCB.setModel(new DefaultComboBoxModel(new String[]{"9", "18"}));
    }

    private void addHolesPanelComponents() {

    }

    private void initFieldPanelComponents() {
        fieldLbl = new JLabel(FIELD);
        fieldJCB = new GolfComboBox(FieldProvider.INSTANCE.getAllFieldNames());
        fieldId = StringHelper.getFieldByName((String) fieldJCB.getSelectedItem()).getId();
        fieldJCB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fieldId = StringHelper.getFieldByName((String) fieldJCB.getSelectedItem()).getId();
                gamesTM.refreshModel(loadGamesData(fieldId, orderingDate, 0, 24));
            }
        });
        playerNameLbl = new JLabel(PLAYER_NAME);
        playerNameJtf = new GolfTextField();
        filtersLabel = new JLabel(Messages.Order_Filters);
    }

    private void addFieldPanelComponents() {
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.LINE_AXIS));
        leftPanel.add(Box.createRigidArea(new Dimension(10, 5)));
        leftPanel.add(fieldLbl);
        leftPanel.add(Box.createRigidArea(new Dimension(20, 5)));
        leftPanel.add(fieldJCB);

        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.LINE_AXIS));
        rightPanel.add(Box.createRigidArea(new Dimension(10, 5)));
        rightPanel.add(playerNameLbl);
        rightPanel.add(Box.createRigidArea(new Dimension(20, 5)));
        rightPanel.add(playerNameJtf);
        rightPanel.add(Box.createRigidArea(new Dimension(10, 5)));

        fieldPanel.add(leftPanel);
        fieldPanel.add(rightPanel);
    }

    private void addLabelComboBoxPanelComponents() {
        GridBagConstraints constraints = new GridBagConstraints();
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        panel.add(playerNameLbl);
        panel.add( Box.createRigidArea(new Dimension(35,5)));
        panel.add(playerNameJtf);
        panel.add( Box.createRigidArea(new Dimension(330,5)));
        constraints.anchor = GridBagConstraints.WEST;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.insets = new Insets(0,0,20,0);
        labelComboBoxPanel.add(panel);
        ((GridLayout)labelComboBoxPanel.getLayout()).setVgap(20);

        JPanel filterLabelPanel = new JPanel();
        filterLabelPanel.setLayout(new BoxLayout(filterLabelPanel, BoxLayout.X_AXIS));
        filterLabelPanel.add(filtersLabel);
        filterLabelPanel.add(Box.createRigidArea(new Dimension(330,5)));
        constraints.fill = GridBagConstraints.BOTH;
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.insets = new Insets(0,0,10,0);
        labelComboBoxPanel.add(filterLabelPanel);
        ((GridLayout)labelComboBoxPanel.getLayout()).setVgap(5);

        JPanel panel1 = new JPanel();
        panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
        panel1.add(dateLbl);
        panel1.add( Box.createRigidArea(new Dimension(30,5)));
        panel1.add(calendarPanel);
        panel1.add( Box.createRigidArea(new Dimension(359,5)));
        constraints.insets = new Insets(0,0,5,0);
        constraints.gridx = 0;
        constraints.gridy = 2;
        labelComboBoxPanel.add(panel1);

        JPanel panel2 = new JPanel();
        panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
        panel2.add(timeLbl);
        panel2.add( Box.createRigidArea(new Dimension(10,5)));
        panel2.add(gameStartJCB);
        panel2.add( Box.createRigidArea(new Dimension(10,5)));
        panel2.add(timeToLbl);
        panel2.add( Box.createRigidArea(new Dimension(10,5)));
        panel2.add(gameEndToJCB);
        panel2.add( Box.createRigidArea(new Dimension(359,5)));
        constraints.gridx = 0;
        constraints.gridy = 3;
        labelComboBoxPanel.add(panel2);

        JPanel panel3 = new JPanel();
        panel3.setLayout(new BoxLayout(panel3, BoxLayout.X_AXIS));
        panel3.add(fieldLbl);
        panel3.add( Box.createRigidArea(new Dimension(26,5)));
        panel3.add(fieldJCB);
        panel3.add( Box.createRigidArea(new Dimension(360,5)));
        constraints.gridx = 0;
        constraints.gridy = 4;
        labelComboBoxPanel.add(panel3);

        JPanel panel4 = new JPanel();
        panel4.setLayout(new BoxLayout(panel4, BoxLayout.X_AXIS));
        panel4.add(holesLbl);
        panel4.add( Box.createRigidArea(new Dimension(23,5)));
        panel4.add(holesJCB);
        panel4.add( Box.createRigidArea(new Dimension(450,5)));
        constraints.gridx = 0;
        constraints.gridy = 5;
        labelComboBoxPanel.add(panel4);
    }

    private void initGamesTablePanelComponents() {
        initTablesMembers();
        gamesTM = new GolfTableModel(gamesData, gamesColumnNames);
        gamesTM.setEditableColumnIndex(0);
        gamesTable = new GolfTable(gamesTM, true);
        gamesTable.getModel().addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if(e.getColumn() == 0 && e.getFirstRow()>-1){
                    String s = gamesTable.getValueAt(e.getFirstRow(), 8).toString();
                    s = s.substring(0, s.indexOf(" "));
                    Double current = Double.parseDouble(s);
                    Double amount = Double.parseDouble(paidMoneyJTF.getText());
                    if(Boolean.TRUE.equals(gamesTable.getValueAt(e.getFirstRow(), 0))) {
                        amount = amount + current;
                    } else{
                        amount = amount - current;
                    }
                    paidMoneyJTF.setText(amount.toString());
                }
            }
        });
        gamesJSP = new ScrollPanel(gamesTable);
        initGamesTableCustomizedColumn(gamesTable);
        GolfCheckBox checkBox = new GolfCheckBox("");
        TableColumn tableColumn = gamesTable.getColumnModel().getColumn(0);
        tableColumn.setCellEditor(new DefaultCellEditor(checkBox));
        gamesJSP = new ScrollPanel(gamesTable);
        gamesJSP.setCorner(JScrollPane.UPPER_RIGHT_CORNER, ComponentsHelper.createBlackScrollCorner());
    }

    private void addGamesTablePanelComponents() {
        gamesTablePanel.add(gamesJSP);
    }

    private void initEquipmentTablePanelComponents() {
        initTablesMembers();
        equipmentsTable = new GolfTable();
        equipmentsTable.setShowListIcon(false);
        equipmentsJSP = new ScrollPanel(equipmentsTable);
        equipmentsTM = new GolfTableModel(equipmentsData, equipmentsColumnNames);
        equipmentsTM.setEditableColumnIndex(0);
        equipmentsTM.setEditableColumnIndex(3);
        equipmentsTM.addTableModelListener(new EquipmentAmountChangeListener());
        equipmentsTable = new GolfTable(equipmentsTM);
        equipmentsTable.getModel().addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if(e.getColumn() == 0 && e.getFirstRow()>-1){
                    String s = equipmentsTable.getValueAt(e.getFirstRow(), 4).toString();
                    s = s.substring(0, s.indexOf(" "));
                    Double current = Double.parseDouble(s);
                    Double amount = Double.parseDouble(paidMoneyJTF.getText());
                    if(Boolean.TRUE.equals(equipmentsTable.getValueAt(e.getFirstRow(), 0))) {
                        amount = amount + current;
                    }else{
                        amount = amount - current;
                    }
                    paidMoneyJTF.setText(amount.toString());
                }
            }
        });
        initEquipmentsTableCustomizedColumn(equipmentsTable);

        GolfCheckBox checkBox = new GolfCheckBox("");
        TableColumn tableColumn = equipmentsTable.getColumnModel().getColumn(0);
        tableColumn.setCellEditor(new DefaultCellEditor(checkBox));

        GolfDecimalTextField textField = new GolfDecimalTextField();
        TableColumn amountColumn = equipmentsTable.getColumnModel().getColumn(3);
        amountColumn.setCellEditor(new DefaultCellEditor(textField));

        equipmentsJSP = new ScrollPanel(equipmentsTable);
        equipmentsJSP.setCorner(JScrollPane.UPPER_RIGHT_CORNER, ComponentsHelper.createBlackScrollCorner());
    }

    private void addEquipmentTablePanelComponents() {
        equipmentTablePanel.add(equipmentsJSP);
    }

    private void initPaidMoneyPanelComponents() {
        paidMoneyLbl = new JLabel();
        paidMoneyLbl.setText(Messages.AddOrderView_Amount);
        paidMoneyJTF = new GolfDecimalTextField();
        paidMoneyJTF.setText("0.0");
        paidMoneyJTF.setEditable(false);
    }

    private void addPaidMoneyPanelComponents() {
        paidMoneyPanel.add(Box.createRigidArea(new Dimension(10, 5)));
        paidMoneyPanel.add(paidMoneyLbl);
        paidMoneyPanel.add(Box.createRigidArea(new Dimension(20, 5)));
        paidMoneyPanel.add(paidMoneyJTF);
        paidMoneyPanel.add(Box.createRigidArea(new Dimension(10, 5)));
    }

    private void initButtonPanelComponents() {
        addBookingButton = new GolfRoundButton(Messages.AddOrderView_AddOrder, Colors.BLUE_BUTTON_BACKGROUND, Colors.BUTTON_FOREGROUND
                , Colors.BLUE_BUTTON_BORDER, Dimensions.DIALOG_EDIT_BUTTON_DIM);
        addBookingButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    checkOut();
                    Order order = createOrder();
                    if (order.getOrderedGames() == null
                            || order.getOrderedGames().isEmpty()) {
                        JOptionPane.showMessageDialog(dialog, Messages.AddOrderView_NoGameSelected
                                , Messages.AddOrderView_Warning, JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    OrderProvider.INSTANCE.addOrder(order);
                    setVisible(false);

                    OrderFilter filter = new OrderFilter();
                    orderTablePanel.initList(OrderProvider.INSTANCE.getFilteredOrders(filter));
                    orderTablePanel.setCalendarData(BookingPanel.calendar.getTime());
                } catch (Exception e1) {
                    System.err.println("Adding booking exception");
                    e1.printStackTrace();
                }
            }
        });
    }

    private void addButtonPanelComponents() {
        buttonPanel.add(Box.createRigidArea(new Dimension(200, 0)));
        buttonPanel.add(addBookingButton);
    }

    private void addLastPanelComponents() {
        lastPanel.add(paidMoneyPanel);
        lastPanel.add(buttonPanel);
    }

    private void addContentPanelComponents() {
        holderPanel.add(labelComboBoxPanel);
        holderPanel.add(Box.createRigidArea(new Dimension(580, 10)));
        holderPanel.add(gamesTablePanel);
        holderPanel.add(Box.createRigidArea(new Dimension(580, 10)));
        holderPanel.add(equipmentTablePanel);
        holderPanel.add(Box.createRigidArea(new Dimension(580, 10)));
        holderPanel.add(lastPanel);
        this.contentPanel.add(holderPanel);
    }

    private void initTablesMembers() {
        gamesColumnNames = new String[]{"", TIME, "", FIELD, PLAYERS, "", "", PRICE, TOTAL, ""};
        orderingDate = Calendar.getInstance().getTime();
        gamesData = loadGamesData(fieldId, orderingDate, 0, 24);

        equipmentsColumnNames = new String[]{"", EQUIPMENT, PRICE, AMOUNT, TOTAL, ""};
        equipmentsData = loadEquipmentData();

    }

    public List<Object[][]> loadGamesData(Long fieldId, Date date, int gameStart, int gameEnd) {
        List<Game> games = GameProvider.INSTANCE.getGamesOnFieldAtDateTime(fieldId, date
                , gameStart, gameEnd);
        List<Object[][]> data = new ArrayList<>();
        for (Game game : games) {
            Object[][] tableRow = new Object[1][gamesColumnNames.length];
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(game.getStartAt());
            int startAtHours = calendar.get(Calendar.HOUR_OF_DAY);
            int startAtMinutes = calendar.get(Calendar.MINUTE);
            calendar.setTime(game.getEndAt());
            int endAtHours = calendar.get(Calendar.HOUR_OF_DAY);
            int endAtMinutes = calendar.get(Calendar.MINUTE);

            tableRow[0][0] = Boolean.FALSE;
//            tableRow[0][1] = String.valueOf(game.getGameStart()) + ":00-"
//                    + String.valueOf(game.getGameEnd()) + ":00";
            tableRow[0][1] = StringHelper.formatTime(startAtHours, startAtMinutes, null, null);
            tableRow[0][2] = StringHelper.buildDaysOfWeek(game);
            tableRow[0][3] = ClubProvider.getClub().getName()
                    + ", "
                    + GameProvider.INSTANCE.getFieldName((int) game
                    .getGolfFieldId());
            tableRow[0][4] = String.valueOf(game.getPlayers())
                    + Messages.PricesViewListGame_clients;
            tableRow[0][5] = new ImageIcon(ImageHelper.getInstance().loadImage(Icons.GOLF_CAR_ICON));
            tableRow[0][6] = new ImageIcon(ImageHelper.getInstance().loadImage(Icons.HOLE_ICON));
            tableRow[0][7] = String.valueOf(game.getPrice()) + " "
                    + ClubProvider.getClub().getCurrency();
            tableRow[0][8] = Double.toString(game.getPrice() * game.getPlayers()) + " "
                    + ClubProvider.getClub().getCurrency();
            tableRow[0][9] = Long.toString(game.getId());
            data.add(tableRow);
        }
        return data;
    }

    public List<Object[][]> loadEquipmentData() {
        List<Equipment> equipments = EquipmentProvider.INSTANCE
                .getEquipments();
        List<Object[][]> data = new ArrayList<>();
        for (Equipment equipment : equipments) {
            Object[][] tableRow = new Object[1][equipmentsColumnNames.length];
            tableRow[0][0] = Boolean.FALSE;
            tableRow[0][1] = equipment.getName();
            tableRow[0][2] = Double.toString(equipment.getPrice()).concat(" ")
                    .concat(ClubProvider.getClub().getCurrency());
            tableRow[0][3] = "1";
            tableRow[0][4] = Double.toString(equipment.getPrice()).concat(" ")
                    .concat(ClubProvider.getClub().getCurrency());
            tableRow[0][5] = Long.toString(equipment.getId());

            data.add(tableRow);
        }
        return data;
    }

    private void checkOut() {
        gamesPrice = 0.0;
        orderedGames = new ArrayList<>();
        int gamesCount = gamesTM.getRowCount();
        for (int i = 0; i < gamesCount; i++) {
            if ((Boolean)gamesTable.getValueAt(i, 0)) {
                long gameId = Long.parseLong((String) gamesTable.getValueAt(i, 9));
                OrderedGame orderedGame = new OrderedGame(GameProvider.INSTANCE.getGameById(gameId));
                gamesPrice += orderedGame.getPrice();
                orderedGames.add(orderedGame);
            }
        }

        equipmentPrice = 0.0;
        orderedEquipment = new ArrayList<>();
        int equipmentAmount = equipmentsTM.getRowCount();
        for (int i = 0; i < equipmentAmount; i++) {
            if ((Boolean)equipmentsTable.getValueAt(i, 0)) {
                int equipmentId = Integer.parseInt((String) equipmentsTable.getValueAt(i, 5));
                int amount = Integer.parseInt((String) equipmentsTable.getValueAt(i, 3));
                Equipment equipment = EquipmentProvider.INSTANCE.getEquipment(equipmentId);
                equipmentPrice += equipment.getPrice() * amount;
                EquipmentSetItem equipmentSetItem = new EquipmentSetItem((long)equipmentId, amount);
                orderedEquipment.add(equipmentSetItem);
            }
        }
        orderPrice = gamesPrice + equipmentPrice;
    }

    private Order createOrder() {
        Order order = new Order();
        order.setClubId(ApplicationConfigValues.CLUB_ID);
        order.setUserId(ApplicationConfigValues.USER_ID);
        order.setPrice(orderPrice);
        order.setEquipmentPrice(equipmentPrice);
        order.setUserName(playerNameJtf.getText());
        for (OrderedGame game : orderedGames) {
            int timeStartSelected = 0;
            try {
                timeStartSelected = Integer.parseInt((String) gameStartJCB.getSelectedItem());
            } catch (NumberFormatException e) {
                timeStartSelected = 0;
            }
            if (timeStartSelected >= game.getStart()) {
                game.setStart(timeStartSelected);
            }
            int timeEndSelected = 0;
            try {
                timeEndSelected = Integer.parseInt((String) gameEndToJCB.getSelectedItem());
            } catch (NumberFormatException e) {
                timeEndSelected = 0;
            }
            if (timeEndSelected <= game.getEnd()) {
                game.setEnd(timeEndSelected);
            }
            game.setHoles(Integer.parseInt((String) holesJCB.getSelectedItem()));
        }
        order.setOrderedGames(orderedGames);
        order.setEquipmentSet(orderedEquipment);
        Double paid = 0.0;
        try {
            paid = Double.parseDouble(paidMoneyJTF.getText());
        } catch (NumberFormatException e) {
            System.err.println("wrong format");
        }
        order.setPaid(paid);
        order.setDate(DateTimeHelper.dateToString(orderingDate, DateTimeHelper.DATE_TYPE_REST));
        order.setStatus(Order.STATUS_PENDING);
        order.setSite(false);
        order.setCreatedAt(ApplicationConfigValues.API_DATE_TIME_FORMAT
                .format(new Date()));
        return order;
    }

    private void initGamesTableCustomizedColumn(GolfTable table) {
        table.customizedColumnSize(0, 20, 20);
        table.customizedColumnSize(1, 40, 80);
        table.customizedColumnSize(2, 50, null);
        table.customizedColumnSize(3, 50, null);
        table.customizedColumnSize(4, 60, 100);
        table.customizedColumnSize(5, 20, 30);
        table.customizedColumnSize(6, 20, 30);
        table.customizedColumnSize(7, 40, null);
        table.customizedColumnSize(8, 40, null);
        table.customizedColumnSize(9, 0, 0);
    }

    private void initEquipmentsTableCustomizedColumn(GolfTable table) {
        table.customizedColumnSize(0, 30, 30);
        table.customizedColumnSize(1, 150, null);
        table.customizedColumnSize(2, 50, null);
        table.customizedColumnSize(3, 70, null);
        table.customizedColumnSize(4, 50, null);
        table.customizedColumnSize(5, 0, 0);

    }

    private String[] getHours() {
        String[] array = new String[24];
        for (int i = 0; i < 24; i++) {
            array[i] = String.valueOf(i);
        }
        return array;
    }

    private class DateChangeListener implements GolfCalendar.CalendarCallback {

        private SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");

        @Override
        public void updateDate(Date date) {
            chosenDateLbl.setText(dateFormat.format(date));
            orderingDate = date;
            gamesTM.refreshModel(loadGamesData(fieldId, date, 0, 24));
        }
    }

    private class  EquipmentAmountChangeListener implements TableModelListener {

        @Override
        public void tableChanged(TableModelEvent e) {
            if (e.getType() == TableModelEvent.UPDATE) {
                int row = e.getFirstRow();
                int column = e.getColumn();
                if (column == 3) {
                    try {
                        int count = Integer.parseInt((String) equipmentsTable.getValueAt(row, 3));
                        int equipmentId = Integer.parseInt((String) equipmentsTable.getValueAt(row, 5));
                        Equipment equipment = EquipmentProvider.INSTANCE.getEquipment(equipmentId);
                        Double totalPrice = count * equipment.getPrice();
                        equipmentsTable.setValueAt(totalPrice.toString().concat(" ").concat(ClubProvider
                                .getClub().getCurrency()), row, 4);
                    } catch (NumberFormatException e1) {
                        equipmentsTable.setValueAt("1", row, column);
                        System.err.println("Wrong value for equipments count");
                    }
                }
            }
        }
    }
}
